package com.suntop.carousel.qlmediaplay.video.player;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.FrameLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
import com.suntop.carousel.qlmediaplay.cache.CacheListener;
import com.suntop.carousel.qlmediaplay.field.Field_Regex;
import com.suntop.carousel.qlmediaplay.field.Field_Scale;
import com.suntop.carousel.qlmediaplay.field.Field_State;
import com.suntop.carousel.qlmediaplay.media.IMediaPlayEventListener;
import com.suntop.carousel.qlmediaplay.media.IMediaPlayer;
import com.suntop.carousel.qlmediaplay.tools.CacheTools;
import com.suntop.carousel.qlmediaplay.video.ui.IRenderView;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

/**
 * 基础的播放控制类
 */
public abstract class QLBasicVideoView extends FrameLayout implements IMediaPlayer
        , IVideoPlayerEventListener, IRenderView.IRenderViewListener, CacheListener {
    private String url = "";
    private AssetFileDescriptor fileDescriptor = null;
    private int scale = Field_Scale.Scale_Default;
    private IMediaPlayEventListener listener;
    private long delayTime = 0;//播放结束后的停留时间
    private boolean autoCache = false;//开启自动缓存
    private boolean isLoop = false;//是否单曲循环
    private float leftVoice, rightVoice;//左右音量
    private boolean isChangeUrl = true;//Url变了吗
    private IVideoPlayer mVideoPLayer;
    private Surface mSurface;
    private IMediaPlayerControl iMediaPlayerControl;//控制
    private IRenderView iRenderView;//播放界面
    private ICoverView iCoverView;//封面
    private boolean isNeedBitmap;//释放需要
    private String error = "";

    private boolean isCanStart = false;
    private boolean isReBack=false;


    public QLBasicVideoView(@NonNull Context context) {
        this(context, null);
    }

    public QLBasicVideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public QLBasicVideoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initVideoView();
    }

    private void initVideoView() {
        isChangeUrl = true;
        iRenderView = getIRenderView();
        iRenderView.addIRenderViewListener(this);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT
                , LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER;
        this.addView(this.iRenderView.getView(), 0, layoutParams);
        iRenderView.setScaleType(scale);
    }

    protected abstract IRenderView getIRenderView();

    @Override
    public IMediaPlayer setReBack(boolean isReBack) {
        this.isReBack=isReBack;
        return this;
    }
    /**
     * 添加封面
     *
     * @param coverView
     * @return
     */
    @Override
    public IMediaPlayer addIConView(ICoverView coverView, boolean catBitmap) {
        if (this.iCoverView != null) {
            this.iCoverView.release();
            removeView(this.iCoverView.coverView());
        }
        this.isNeedBitmap = catBitmap;
        this.iCoverView = coverView;
        addView(this.iCoverView.coverView(), LayoutParams.MATCH_PARENT
                , LayoutParams.MATCH_PARENT);
        return this;
    }

    @Override
    public IMediaPlayer addController(IMediaPlayerControl control) {
        if (this.iMediaPlayerControl != null) {
            this.iMediaPlayerControl.release();
            removeView(this.iMediaPlayerControl.getView());
        }
        iMediaPlayerControl = control;
        if (iMediaPlayerControl != null) {
            if (mVideoPLayer != null)
                iMediaPlayerControl.setMediaPlayer(mVideoPLayer);
            LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT
                    , LayoutParams.MATCH_PARENT);
            layoutParams.gravity = Gravity.BOTTOM;
            addView(iMediaPlayerControl.getView(), layoutParams);
        }
        return this;
    }

    @Override
    public IMediaPlayer init(IVideoPlayer iVideoPlayer) {
        if (this.mVideoPLayer != null && !this.mVideoPLayer.takePlayTag().equals(iVideoPlayer.takePlayTag())) {
            mVideoPLayer.stop();
            mVideoPLayer.release();
            mVideoPLayer = null;
        }
        mVideoPLayer = iVideoPlayer;
        return this;
    }

    @Override
    public IMediaPlayer setVoice(float left, float right) {
        this.leftVoice = left;
        this.rightVoice = right;
        if (mVideoPLayer != null) {
            mVideoPLayer.setVolume(this.leftVoice, this.rightVoice);
        }
        return this;
    }

    @Override
    public IMediaPlayer setLoop(boolean isLoop) {
        this.isLoop = isLoop;
        if (mVideoPLayer != null) {
            mVideoPLayer.setLoop(this.isLoop);
        }
        return this;
    }


    @Override
    public IMediaPlayer addEventListener(IMediaPlayEventListener listener) {
        this.listener = listener;
        return this;
    }

    @Override
    public IMediaPlayEventListener getEventListener() {
        return this.listener;
    }

    @Override
    public IMediaPlayer setDate(String playUrl) {
        if (fileDescriptor != null) {
            fileDescriptor = null;
        }
        if (TextUtils.isEmpty(playUrl)) {
            return this;
        }
        if (!url.equalsIgnoreCase(playUrl)) {
            isChangeUrl = true;
            url = playUrl;
        }
        return this;
    }

    public IMediaPlayer setDate(AssetFileDescriptor fileDescriptor) {
        if (!TextUtils.isEmpty(url)) {
            url = "";
        }
        if (fileDescriptor == null) {
            return this;
        }
        if (this.fileDescriptor != fileDescriptor) {
            isChangeUrl = true;
        }
        this.fileDescriptor = fileDescriptor;
        return this;
    }

    @Override
    public String getPlayUrl() {
        return url;
    }

    @Override
    public IMediaPlayer setScaleType(int scaleType) {
        this.scale = scaleType;
        if (iRenderView != null) {
            iRenderView.setScaleType(scaleType);
        }
        return this;
    }

    @Override
    public int getScale() {
        return this.scale;
    }

    @Override
    public IMediaPlayer setDelayTime(long time) {
        this.delayTime = time;
        return this;
    }

    @Override
    public long getDelayTime() {
        return this.delayTime;
    }

    @Override
    public IMediaPlayer autoCache(boolean auto) {
        this.autoCache = auto;
        return this;
    }

    @Override
    public boolean isPlaying() {
        return mVideoPLayer != null && mVideoPLayer.isOnPlaying();
    }

    @Override
    public void build(boolean isPlayer) {
        if (TextUtils.isEmpty(url) && fileDescriptor == null) {
            if (getEventListener() != null) {
                Log.e("播放器状态", "数据错误" + url);
                error = "播放数据为空,请确认";
                RetryTask();
            }
            return;
        }
        reSetCupPicture();
        Log.e("播放器状态", isPlayer + "构建参数=" + url);
        if (mVideoPLayer == null) {
            mVideoPLayer = getVideoPlayer();
        }
        mVideoPLayer.setIsReBack(isReBack);
        if (isPlaying()) {
            mVideoPLayer.stop();
        }
        mVideoPLayer.reset();
        mVideoPLayer.setVolume(leftVoice,rightVoice);
        if (iRenderView==null){
           return;
        }
        iRenderView.setScaleType(scale);
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.setMediaPlayer(mVideoPLayer);
        }
        mVideoPLayer.setIVideoPlayerEventListener(this);
        isChangeUrl = true;

    }

    private void prepareAsync(boolean isPlayer) {
        isCanStart = isPlayer;
        if (mSurface != null) {
            error = "";
            reSetCupPicture();
//            if (isPlaying()) {
//                mVideoPLayer.stop();
//                Log.e("systemTime2", System.currentTimeMillis() + " ");
//            }
            Log.e("systemTime3", System.currentTimeMillis() + " ");
            isChangeUrl = false;
            mVideoPLayer.reset();
            if (!prepareDataSource()) {
                error = "资源设置错误";
                RetryTask();
                return;
            }
            mVideoPLayer.setIsPrepared(isPlayer);
//            mVideoPLayer.setVolume(leftVoice, rightVoice);
            mVideoPLayer.setLoop(isLoop);
            this.bindSurface(this.mVideoPLayer, this.mSurface);
        }
    }


    private void bindSurface(IVideoPlayer mVideoPLayer, Surface mSurface) {
        mVideoPLayer.setSurface(mSurface);
        mVideoPLayer.prepareAsync();
    }

    protected abstract IVideoPlayer getVideoPlayer();

    private void RetryTask() {
        this.removeCallbacks(task);
        this.postDelayed(task, delayTime);
    }

    private boolean prepareDataSource() {
        if (isLocalDataSource()) {
            if (fileDescriptor != null) {
                mVideoPLayer.setAssetFileDescriptor(fileDescriptor);
            } else if (!TextUtils.isEmpty(url)) {
                mVideoPLayer.setPlayUrl(url);
            }
        } else {
            if (autoCache) {
                //如果自动缓存
                String s = CacheTools.getInStance().registerListener(getContext(), url
                        , this);
                mVideoPLayer.setPlayUrl(s);
            } else {
                mVideoPLayer.setPlayUrl(url);
            }
        }
        return true;
    }

    /**
     * 判断是否为本地数据源，包括 本地文件、Asset、raw
     */
    private boolean isLocalDataSource() {
        if (fileDescriptor != null) {
            return true;
        } else if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);

            return ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
                    || ContentResolver.SCHEME_FILE.equals(uri.getScheme())
                    || "rawresource".equals(uri.getScheme())
                    || isMatchLocation(url);
        }
        return false;
    }

    private boolean isMatchLocation(String url) {
        boolean b = !url.matches(Field_Regex.Url);
        Log.e("正则表达式", "是否正常" + b);
        return !url.matches(Field_Regex.Url);
    }

    /**
     * 是否需要重置播放器
     *
     * @return
     */
    private boolean isNeedBuilt() {
        if (isChangeUrl || mVideoPLayer.isNeedRest()) {
            return true;
        }
        return false;
    }

    /**
     * 不用构造
     *
     * @return
     */
    private boolean canStartNow() {
        if (mVideoPLayer == null) {
            return false;
        }
        if (isChangeUrl){
            return false;
        }
        if (mSurface==null){
            return false;
        }
        if (mVideoPLayer.isOnPlaying()) {
            Log.e("设置2","=============="+mVideoPLayer.getPlayState());
            return true;
        }
        return false;
    }

    @Override
    public void startPlay() {
        if (!canStartNow()) {
            Log.e("准备播放的","111111111");
            prepareAsync(true);
        } else {
            Log.e("开始播放的","2222222");
            mVideoPLayer.start();
            if (mVideoPLayer.isOnPlaying()) {
                if (iCoverView != null) {
                    iCoverView.showVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void pausePlay() {
        if (mVideoPLayer != null) {
            if (mVideoPLayer.isOnPlaying())
                mVideoPLayer.pause();
        }
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.hid();
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void stopPlay() {
        removeCallbacks(task);
        isChangeUrl = true;
        if (iCoverView != null) {
//            if (isNeedBitmap) {
//                iCoverView.showBitmap(iRenderView.doScreenShot());
//            }
            iCoverView.showVisibility(View.VISIBLE);
        }
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.hid();
        }
        if (mVideoPLayer != null) {
            mVideoPLayer.reset();
        }
    }

    @Override
    public void pauseTo() {
        removeCallbacks(task);
        reSetCupPicture();
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.hid();
        }
        if (mVideoPLayer!=null){
            mVideoPLayer.pause();
            mVideoPLayer.seekTo(0);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void releasePlay() {
        if (mVideoPLayer != null) {
            if (mVideoPLayer.isOnPlaying()){
                Log.e("释放","==============");
                mVideoPLayer.stop();
            }
            mVideoPLayer.reset();
            mVideoPLayer.release();
            this.mVideoPLayer = null;
        }
        if (this.mSurface != null) {
            this.mSurface.release();
            this.mSurface = null;
        }
        if (iRenderView != null) {
            iRenderView.release();
            this.removeView(iRenderView.getView());
            iRenderView = null;
        }
        if (iCoverView != null) {
            iCoverView.release();
            this.removeView(iCoverView.coverView());
            iCoverView = null;
        }
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.release();
            this.removeView(iMediaPlayerControl.getView());
            iMediaPlayerControl = null;
        }
        if (autoCache) {
            CacheTools.getInStance().unRegisterListener(getContext(), url, this);
        }
    }

    //这个重置的时候保留界面
    @SuppressLint("NewApi")
    @Override
    public void releaseNoClear() {
        if (mVideoPLayer != null) {
            if (mVideoPLayer.isOnPlaying()){
                mVideoPLayer.stop();
                mVideoPLayer.reset();
            }
            mVideoPLayer.release();
            this.mVideoPLayer = null;
        }
        if (this.mSurface != null) {
            this.mSurface.release();
            this.mSurface = null;
        }
        if (iRenderView != null) {
            iRenderView.release();
            this.removeView(iRenderView.getView());
            iRenderView = null;
        }
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.release();
            this.removeView(iMediaPlayerControl.getView());
        }
        initVideoView();
        if (iMediaPlayerControl != null) {
            this.addView(iMediaPlayerControl.getView(), LayoutParams.MATCH_PARENT
                    , LayoutParams.MATCH_PARENT);
        }
    }

    @Override
    public View getQLView() {
        return this;
    }

    @Override
    public void onError(String tag, String error) {
        if (getEventListener() != null) {

            this.error = "错误内容=" + error;
            RetryTask();
        }


    }

    @Override
    public void onCompletion(String tag) {
//        if (mVideoPLayer != null) {
//            stopPlay();
//        }
        if (getEventListener() != null) {
            error = "结束播放  " + tag;
            Log.e("===", error);
            RetryTask();
        }
    }

    @Override
    public void onPrepared(String tag) {
        if (mVideoPLayer == null) {
            return;
        }
        if (iMediaPlayerControl != null) {
            iMediaPlayerControl.hid();
            iMediaPlayerControl.setDuration((int) mVideoPLayer.getDuration());
            iMediaPlayerControl.setSeekBar((int) mVideoPLayer.getCurrentPosition());
        }
        if (iRenderView != null) {
            iRenderView.setVideoSize(mVideoPLayer.getVideoWidth()
                    , mVideoPLayer.getVideoHeight());
        }

    }

    @Override
    public void reSetCupPicture() {
        if (iCoverView != null) {
            iCoverView.showScaleType(scale);
            iCoverView.showVisibility(View.VISIBLE);
//            iCoverView.release();
//            if (!TextUtils.isEmpty(url))
//                iCoverView.showUrl(url);
        }
    }

    @Override
    public void onInfo(String tag, int what, int extra) {
        if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
            if (getEventListener() != null) {
                getEventListener().startMediaPlay(0, 0
                        , getPlayUrl());
            }
            if (iCoverView != null) {
                iCoverView.showVisibility(GONE);
                iCoverView.showBitmap(iRenderView.doScreenShot());
            }
        }
        if (what == 10001) {
            if (iRenderView != null) iRenderView.setVideoRotation(extra);
        }
    }

    @Override
    public void onVideoSizeChanged(String tag, int width, int height) {
        if (width > 0 && height > 0) {
            if (iRenderView != null) {
                iRenderView.setVideoSize(width, height);
            }
        }
    }

    @Override
    public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
        if (percentsAvailable == 100) {
            if (getEventListener() != null) {
                getEventListener().cacheMediaPlay(0, 0
                        , url, cacheFile.getPath());
            }
        }
    }

    @Override
    public void setSurfaceView(Surface surface) {
        this.mSurface = surface;
        Log.e("生成","setSurfaceView");
        if (isCanStart){
            prepareAsync(true);
        }
    }

    @Override
    public void setSurfaceHolder(SurfaceHolder surfaceHolder) {
        this.mSurface = surfaceHolder.getSurface();
        Log.e("生成","setSurfaceHolder");
        if (isCanStart){
            prepareAsync(true);
        }

    }

    @Override
    public void destroySurfaceView(Surface surface) {
        if (this.mVideoPLayer != null && this.mVideoPLayer.getPlayState()
                != Field_State.DESTROYED) {
            this.mVideoPLayer.setDisplay(null);
        }
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        if (mVideoPLayer != null && mVideoPLayer.isOnPlaying()
                && this.iMediaPlayerControl != null) {
            this.toggleMediaControlsVisibility();
        }
        return super.onTrackballEvent(event);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mVideoPLayer != null && mVideoPLayer.isOnPlaying()
                && this.iMediaPlayerControl != null) {
            this.toggleMediaControlsVisibility();
        }
        return super.onTouchEvent(event);
    }

    private void toggleMediaControlsVisibility() {
        if (this.iMediaPlayerControl.isShow()) {
            this.iMediaPlayerControl.hid();
        } else {
            this.iMediaPlayerControl.show();
        }
    }

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (getEventListener() != null) {
                getEventListener().finishMediaPlay(0, 0
                        , url, error);
            }
        }
    };

}
